package com.example.security.config;

import com.example.security.bean.SysPermission;
import com.example.security.bean.SysRole;
import com.example.security.dao.SysPermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 */
@Component
public class MySecurityFilter implements FilterInvocationSecurityMetadataSource {

    /**
     * 路径匹配器
     */
    AntPathMatcher pathMatcher = new AntPathMatcher();


    @Autowired
    SysPermissionMapper sysPermissionMapper;


    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //当前请求URl
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        //      数据库中所有url
        List<SysPermission> sysPermissionList = sysPermissionMapper.getAllList();

        //要拦截的url
        List<SysPermission> sysPermissions=sysPermissionList.stream().filter(sysPermission -> sysPermission.getState().equals("0")).collect(Collectors.toList());
        for (SysPermission sysPermission : sysPermissions) {
            if (pathMatcher.match(sysPermission.getUrl(), requestUrl)) {
                List<SysRole> roles = sysPermission.getSysRoleList();
                String[] rolesStr = new String[roles.size()];
                for (int i = 0; i < roles.size(); i++) {
                    rolesStr[i] = roles.get(i).getRole();
                }
                // 保存该url对应角色权限信息
                return SecurityConfig.createList(rolesStr);
            }
        }
        //标记非法请求
        return SecurityConfig.createList("ROLE_login");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    /**
     * 开启支持
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
